package cn.tedu.car.backend.customer.service.impl;

import cn.tedu.car.backend.base.exception.ServiceException;
import cn.tedu.car.backend.base.response.PageData;
import cn.tedu.car.backend.base.response.StatusCode;
import cn.tedu.car.backend.customer.config.SmsConfiguration;
import cn.tedu.car.backend.customer.dao.cache.CustomerCacheRepository;
import cn.tedu.car.backend.customer.dao.repository.CustomerInfoRepository;
import cn.tedu.car.backend.customer.dao.repository.CustomerRepository;
import cn.tedu.car.backend.customer.pojo.dto.CustomerAddDto;
import cn.tedu.car.backend.customer.pojo.dto.CustomerQueryParam;
import cn.tedu.car.backend.customer.pojo.dto.CustomerRegDto;
import cn.tedu.car.backend.customer.pojo.dto.IdentifyDto;
import cn.tedu.car.backend.customer.pojo.entity.Customer;
import cn.tedu.car.backend.customer.pojo.entity.CustomerInfo;
import cn.tedu.car.backend.customer.pojo.vo.CustomerDetailVo;
import cn.tedu.car.backend.customer.pojo.vo.CustomerListVo;
import cn.tedu.car.backend.customer.pojo.vo.CustomerLoginInfoVO;
import cn.tedu.car.backend.customer.pojo.vo.IdentifyResultVO;
import cn.tedu.car.backend.customer.service.CustomerService;
import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;

/**
 * @author LLY
 */
@Slf4j
@Service
public class CustomerServiceImpl implements CustomerService {

    int CAPTCHA_LENGTH = 4;
    /**
     * 短信发送成功状态码
     */
    String MESSAGE_SEND_SUCCESS="000000";
    String IDENTIFY_SUCCESS="0";


    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private CustomerCacheRepository customerCacheRepository;

    @Autowired
    private CustomerInfoRepository customerInfoRepository;


    @Override
    public PageData list(CustomerQueryParam param) {
      log.debug("开始处理【查询客户列表】的业务处理，页码：{}，每页记录数：{}", param.getPageNum(), param.getPageSize());
          return customerRepository.list(param);
    }

    @Override
    public CustomerLoginInfoVO login(String username, String password) {
        log.debug("开始处理【登录】的业务处理，用户名：{}，密码：{}", username, password);
       Customer customer = customerRepository.getCustomerByUsername(username);
       if (customer == null) {
           throw new ServiceException(StatusCode.VALIDATE_ERROR);
       }
       if (!customer.getPassword().equals(password)) {
           throw new ServiceException(StatusCode.VALIDATE_ERROR);
       }
       CustomerLoginInfoVO customerLoginInfoVO = new CustomerLoginInfoVO();
       customerLoginInfoVO.setId(customer.getId());
       customerLoginInfoVO.setUsername(customer.getUsername());
       customerLoginInfoVO.setNickname(customer.getNickname());
       return customerLoginInfoVO;
    }

    @Override
    public void register(CustomerRegDto customerRegDto) {
        log.debug("开始处理【注册】的业务处理，参数：{}", customerRegDto);
        Customer customer = customerRepository.getCustomerByUsername(customerRegDto.getUsername());
        if (customer != null) {
            throw new RuntimeException("用户名已存在");
        }
        customer = new Customer();
        customer.setUsername(customerRegDto.getUsername());
        customer.setPassword(customerRegDto.getPassword());
        customer.setState(1);
        customer.setCreateTime(LocalDateTime.now());
        customerRepository.insert(customer);
    }

    @Override
    public void sendCaptcha(String phone) {
        String msgCode = generateRandomCode();
        String[] params = {msgCode, "5"};
        log.debug("随机验证码为: {}", msgCode);
        sendMsg(phone, "1", params);
        customerCacheRepository.saveCaptcha(msgCode, phone);
    }

    @Override
    public void loginWithPhone(String phone, String code) {
        log.debug("开始处理【用户登录--手机验证】的业务，参数：{}{}",phone,code);
        Customer customer = customerRepository.getCustomerByPhone(phone);
        if (!customerCacheRepository.getRandomCode(phone).equals(code)) {
            throw new ServiceException(StatusCode.VALIDATE_ERROR);
        }
        if (customerCacheRepository.getRandomCode(phone) == null) {
            throw new ServiceException(StatusCode.VALIDATE_ERROR);
        }
    }

    @Override
    public void  identify(IdentifyDto identifyDto) throws IOException {
        //通过用户id获取用户信息
        Customer customer = customerRepository.getCustomerById(identifyDto.getCustomerId());
        if (customer == null){
            //用户不存在
            throw new ServiceException(StatusCode.VALIDATE_ERROR);
        }
        if (customer.getIsIdentity() == 1){
            //该用户已经实名
            throw new ServiceException(StatusCode.VALIDATE_ERROR);
        }

        String url = "https://eid.shumaidata.com/eid/check";
        String appCode = "ab1da0d574ab4bc2b0de9538f1ccdbca";
        Map<String, String> params = new HashMap<>();
        params.put("idcard", identifyDto.getPersonNum());
        params.put("name", identifyDto.getName());
        String result = postForm(appCode, url, params);
        ObjectMapper mapper = new ObjectMapper();
        IdentifyResultVO identifyResultVO = mapper.readValue(result, IdentifyResultVO.class);
        if (!IDENTIFY_SUCCESS.equals(identifyResultVO.getCode())){
            //验证失败
            throw new ServiceException(StatusCode.VALIDATE_ERROR);
        }
        Customer customer1 = new Customer();
        customer1.setId(identifyDto.getCustomerId());
        customer1.setIsIdentity(1);
        customer1.setUpdateTime(LocalDateTime.now());
        customerRepository.update(customer1);

        CustomerInfo customerInfo = new CustomerInfo();
        customerInfo.setCustomerId(identifyDto.getCustomerId());
        customerInfo.setPersonNum(identifyDto.getPersonNum());
        customerInfo.setName(identifyDto.getName());
        customerInfo.setUpdateTime(LocalDateTime.now());
        customerInfo.setCreateTime(LocalDateTime.now());
        int row = customerInfoRepository.insert(customerInfo);
        if (row != 1){
            throw new ServiceException(StatusCode.VALIDATE_ERROR);
        }
    }

    @Override
    public CustomerDetailVo getCustomerById(Long id) {
        return customerRepository.getCustomerDetailById(id);
    }

    @Override
    public void changeStateById(Long id) {
        Customer customerById = customerRepository.getCustomerById(id);
        Customer customer = new Customer();
        customer.setId(id);
        if (customerById.getState() == 1){
            customer.setState(0);
        }else {
            customer.setState(1);
        }
        customerRepository.update(customer);
    }

    @Override
    public void add(CustomerAddDto customerAddDto) {
        
    }

    /**
     * 发送短信
     *
     * @param mobile     手机号
     * @param templateId 短信模板编号
     * @param params     短信模板参数
     */
    private void sendMsg(String mobile, String templateId, String[] params) {

        //创建sdk客户端对象
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        //初始化客户端对象
        sdk.init(SmsConfiguration.SERVER_IP, SmsConfiguration.SERVER_PORT);
        //属性赋值
        sdk.setAccount(SmsConfiguration.ACCOUNT_ID, SmsConfiguration.ACCOUNT_TOKEN);
        sdk.setAppId(SmsConfiguration.APP_ID);
        sdk.setBodyType(BodyType.Type_JSON);
        //可选 扩展码，四位数字 0~9999
        String subAppend = generateRandomCode();
        Object resultCd = null;
        String resultMsg = null;
        try {
            HashMap<String, Object> result = sdk.sendTemplateSMS(mobile, templateId, params);
            resultCd = result.get("statusCode");
            if (MESSAGE_SEND_SUCCESS.equals(resultCd)) {
                //正常返回输出data包体信息（map）
                HashMap<String, Object> data = (HashMap<String, Object>) result.get("data");
                Set<String> keySet = data.keySet();
                for (String key : keySet) {
                    Object object = data.get(key);
                    System.out.println(key + " = " + object);
                }
            } else {
                //异常返回输出错误码和错误信息
                log.info("错误码>>" + resultCd + " 错误信息>> " + resultMsg);
            }
        } catch (Exception e) {
            if (resultCd != null) {
                throw new ServiceException(StatusCode.VALIDATE_ERROR);
            } else {
                throw new ServiceException(StatusCode.VALIDATE_ERROR);
            }
        }
    }

    /**
     * 生成随机四位验证码
     */
    private String generateRandomCode() {
        StringBuilder code = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < CAPTCHA_LENGTH; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }

    private String postForm(String appCode, String url, Map<String, String> params) throws IOException {
        OkHttpClient client = new OkHttpClient.Builder().build();
        FormBody.Builder formbuilder = new FormBody.Builder();
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next();
            formbuilder.add(key, params.get(key));
        }
        FormBody body = formbuilder.build();
        Request request = new Request.Builder().url(url).addHeader("Authorization", "APPCODE " + appCode).post(body).build();
        Response response = client.newCall(request).execute();
        System.out.println("返回状态码" + response.code() + ",message:" + response.message());
        String result = response.body().string();
        return result;
    }
}
